App Structure
Part 1, Chapter 7
With tests in place, let's refactor the app, adding in FastAPI's APIRouter, a new database init function, and a pydantic model.
APIRouter
First, add a new folder called "api" to the "app" folder. Add an __init__.py file to the newly created folder.
Now we can move the /ping route to a new file called project/app/api/ping.py:
# project/app/api/ping.py
from fastapi import APIRouter, Depends
from app.config import get_settings, Settings
router = APIRouter()
@router.get("/ping")
async def pong(settings: Settings = Depends(get_settings)):
return {
"ping": "pong!",
"environment": settings.environment,
"testing": settings.testing
}
Then, update main.py like so to remove the old route, wire the router up to our main app, and use a function to initialize a new app:
# project/app/main.py
import os
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from app.api import ping
def create_application() -> FastAPI:
application = FastAPI()
register_tortoise(
application,
db_url=os.environ.get("DATABASE_URL"),
modules={"models": ["app.models.tortoise"]},
generate_schemas=False,
add_exception_handlers=True,
)
application.include_router(ping.router)
return application
app = create_application()
Make sure http://localhost:8004/ping and http://localhost:8004/docs still work.
Update the test_app fixture in project/tests/conftest.py to use the create_application function to create a new instance of FastAPI for testing purposes:
# project/tests/conftest.py
import os
import pytest
from starlette.testclient import TestClient
from app.main import create_application # updated
from app.config import get_settings, Settings
def get_settings_override():
return Settings(testing=1, database_url=os.environ.get("DATABASE_TEST_URL"))
@pytest.fixture(scope="module")
def test_app():
# set up
app = create_application() # new
app.dependency_overrides[get_settings] = get_settings_override
with TestClient(app) as test_client: # updated
# testing
yield test_client
# tear down
Make sure the tests still pass:
$ docker-compose exec web python -m pytest
=============================== test session starts ===============================
platform linux -- Python 3.10.1, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /usr/src/app
plugins: anyio-3.4.0
collected 1 item
tests/test_ping.py . [100%]
================================ 1 passed in 0.16s ================================
You can break up and modularize larger projects as well as apply versioning to your API with the
APIRouter. If you're familiar with Flask, it's equivalent to a Blueprint.
Your project structure should now look like:
├── .gitignore
├── docker-compose.yml
└── project
├── .dockerignore
├── Dockerfile
├── app
│ ├── __init__.py
│ ├── api
│ │ ├── __init__.py
│ │ └── ping.py
│ ├── config.py
│ ├── db.py
│ ├── main.py
│ └── models
│ ├── __init__.py
│ └── tortoise.py
├── db
│ ├── Dockerfile
│ └── create.sql
├── entrypoint.sh
├── migrations
│ └── models
│ └── 0_20211227001140_init.sql
├── pyproject.toml
├── requirements.txt
└── tests
├── __init__.py
├── conftest.py
└── test_ping.py
Database Init
Next, let's move the register_tortoise helper to project/app/db.py to clean up project/app/main.py:
# project/app/db.py
import os
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
TORTOISE_ORM = {
"connections": {"default": os.environ.get("DATABASE_URL")},
"apps": {
"models": {
"models": ["app.models.tortoise", "aerich.models"],
"default_connection": "default",
},
},
}
def init_db(app: FastAPI) -> None:
register_tortoise(
app,
db_url=os.environ.get("DATABASE_URL"),
modules={"models": ["app.models.tortoise"]},
generate_schemas=False,
add_exception_handlers=True,
)
Import init_db into main.py:
# project/app/main.py
import logging
from fastapi import FastAPI
from app.api import ping
from app.db import init_db
log = logging.getLogger("uvicorn")
def create_application() -> FastAPI:
application = FastAPI()
application.include_router(ping.router)
return application
app = create_application()
@app.on_event("startup")
async def startup_event():
log.info("Starting up...")
init_db(app)
@app.on_event("shutdown")
async def shutdown_event():
log.info("Shutting down...")
Here, we added startup and shutdown event handlers, which get executed before the app starts up or when the app shuts down, respectively.
To test, first bring down the containers and volumes:
$ docker-compose down -v
Then, bring the containers back up:
$ docker-compose up -d --build
Since we haven't applied the migrations, you shouldn't see any tables in the database:
$ docker-compose exec web-db psql -U postgres
psql (14.1)
Type "help" for help.
postgres=# \c web_dev
You are now connected to database "web_dev" as user "postgres".
web_dev=# \dt
Did not find any relations.
web_dev=# \q
Rather than applying the migrations via Aerich, which can be slow, there may be times where you just want to apply the schema to the database in its final state. So, let's add a generate_schema function to db.py for handling that:
# project/app/db.py
import logging # new
import os
from fastapi import FastAPI
from tortoise import Tortoise, run_async # new
from tortoise.contrib.fastapi import register_tortoise
log = logging.getLogger("uvicorn") # new
TORTOISE_ORM = {
"connections": {"default": os.environ.get("DATABASE_URL")},
"apps": {
"models": {
"models": ["app.models.tortoise", "aerich.models"],
"default_connection": "default",
},
},
}
def init_db(app: FastAPI) -> None:
register_tortoise(
app,
db_url=os.environ.get("DATABASE_URL"),
modules={"models": ["app.models.tortoise"]},
generate_schemas=False,
add_exception_handlers=True,
)
# new
async def generate_schema() -> None:
log.info("Initializing Tortoise...")
await Tortoise.init(
db_url=os.environ.get("DATABASE_URL"),
modules={"models": ["models.tortoise"]},
)
log.info("Generating database schema via Tortoise...")
await Tortoise.generate_schemas()
await Tortoise.close_connections()
# new
if __name__ == "__main__":
run_async(generate_schema())
So, generate_schema calls Tortoise.init to set up Tortoise and then generates the schema.
Run:
$ docker-compose exec web python app/db.py
You should now see the schema:
$ docker-compose exec web-db psql -U postgres
psql (14.1)
Type "help" for help.
postgres=# \c web_dev
You are now connected to database "web_dev" as user "postgres".
web_dev=# \dt
List of relations
Schema | Name | Type | Owner
--------+-------------+-------+----------
public | textsummary | table | postgres
(1 row)
web_dev=# \q
Finally, since we do want to use Aerich in dev to manage the database schema, bring the containers and volumes down again:
$ docker-compose down -v
bring the containers back up:
$ docker-compose up -d --build
Confirm that the table doesn't exist in the database. Then, apply the migration:
$ docker-compose exec web aerich upgrade
Confirm that the aerich and textsummary tables now exist.
Pydantic Model
First time using pydantic? Review the Overview guide from the official docs.
Create a SummaryPayloadSchema pydantic model with one required field -- a url -- in a new file called pydantic.py in "project/app/models":
# project/app/models/pydantic.py
from pydantic import BaseModel
class SummaryPayloadSchema(BaseModel):
url: str
We'll use this model in the next chapter.
✓ Mark as Completed